package com.gmics.unifiq.fragment;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.gmics.android.R;
import com.gmics.unifiq.MainActivity;
import com.gmics.unifiq.ViewOpenEvent;
import com.gmics.unifiq.adapter.HomeAdapter;
import com.gmics.unifiq.controller.EntityController;
import com.gmics.unifiq.controller.UserFunctions;
import com.gmics.unifiq.entity.Avatar;
import com.gmics.unifiq.entity.Notification;
import com.gmics.unifiq.entity.OpenEvent;
import com.gmics.unifiq.entity.User;
import com.gmics.unifiq.entity.UserNotification;
import com.gmics.unifiq.menu.Account;
import com.gmics.unifiq.menu.FAQ;

public class HomeFragment extends Fragment {
	private EntityController controller = new EntityController();
	private TextView notification;
	private GridView mainGV;
	private ProgressDialog pDialog = null;
	private ArrayList<OpenEvent> oeArr = new ArrayList<OpenEvent>();
	private boolean dialogValid = false;
	private Notification n;
	private OpenEvent nEvent;
	private ArrayList<UserNotification> unArr;
	private Avatar avatar;
	private Bitmap bm;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater
				.inflate(R.layout.home_layout, container, false);

		new LoadAllOpenEvent().execute();

		return rootView;
	}

	@Override
	public void onPause() {
		super.onPause();
		if (pDialog != null)
			pDialog.dismiss();
	}

	class LoadAllOpenEvent extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			
		    int index = ((MainActivity) getActivity()).getCurrentFragment();
		    if (index == 0){
				pDialog = new ProgressDialog(getActivity());
				pDialog.setMessage("Loading page...");
				pDialog.setIndeterminate(false);
				pDialog.setCancelable(false);
				pDialog.show();
				dialogValid = true;
		    }
		}

		@Override
		protected String doInBackground(String... args) {
    		UserFunctions uf = new UserFunctions();
    		HashMap<String, String> user = uf.getUser(getActivity());
    		User tempUser = controller.retrieveUser(user.get("uid"));
    		
    		unArr = controller.retrieveUserNotification(tempUser.getId());
			avatar = controller.retrieveAvatar(tempUser.getAvatarID());
    		oeArr = controller.retrieveOpenEvent();
			n = controller.retrieveLatestOpenEventNotification();
			nEvent = controller.retrieveOpenEventByID(n.getOpenEventID());
			
			try {
				 URL url = new URL(avatar.getIconPath()); 
				 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
				 connection.setRequestMethod("POST");
				 connection.setRequestProperty("Connection", "close"); 
				 connection.connect();
				 bm = BitmapFactory.decodeStream(connection.getInputStream());		
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		@Override
		protected void onPostExecute(String file_url) {
			if (dialogValid){
				pDialog.dismiss();
				notification = (TextView) getActivity().findViewById(
						R.id.notification_tv);
				notification.setVisibility(TextView.VISIBLE);
				
			}
			getActivity().runOnUiThread(new Runnable() {
				@Override
				public void run() {
					LayoutInflater inflater = getActivity().getLayoutInflater();
					View layout = inflater.inflate(R.layout.avatar_toast,
					                               (ViewGroup) getActivity().findViewById(R.id.avatar_toast_ll));

					int unread = 0;
					for (int i = 0; i < unArr.size(); i++){
						if (!unArr.get(i).isRead()){
							unread++;
						}
					}
					
					if (unread != 0){
						TextView avatarText = (TextView) layout.findViewById(R.id.avatar_tv);
						ImageView avatarIcon = (ImageView) layout.findViewById(R.id.avatar_icon);
						avatarIcon.setImageBitmap(bm);
						avatarText.setText("You have " + String.valueOf(unread) + " pending notifications!");
	
						Toast toast = new Toast(getActivity().getApplicationContext());
						//toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
						toast.setDuration(Toast.LENGTH_LONG);
						toast.setView(layout);
						toast.show();
					}
					
					mainGV = (GridView) getActivity()
							.findViewById(R.id.main_gv);
					mainGV.setAdapter(new HomeAdapter(getActivity(), oeArr));

					mainGV.setOnItemClickListener(new OnItemClickListener() {
						@Override
						public void onItemClick(AdapterView<?> parent, View v,
								int position, long id) {

							int imgPos = position
									% HomeAdapter.getImageArr().length;
							Bundle b = new Bundle();
							b.putSerializable("selectedOpenEvent",
									oeArr.get(position));
							Intent eventScreen = new Intent(getActivity(),
									ViewOpenEvent.class);
							eventScreen.putExtras(b);
							eventScreen.putExtra("imgPos", imgPos);
							startActivity(eventScreen);

						}
					});


					notification.setPadding(40, 30, 40, 30);
					notification.setTextSize(20);
					notification.setGravity(Gravity.CENTER);

					notification
							.setText("UPDATE! " + nEvent.getName() + " @ " + nEvent.getLocation() + " has been shifted to " + EntityController.convertDateTimeToString(nEvent.getDateTime()) + "!");
					notification.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View arg0) {
							Bundle b = new Bundle();
							b.putSerializable("selectedOpenEvent", nEvent);
							Intent eventScreen = new Intent(getActivity(),
									ViewOpenEvent.class);
							eventScreen.putExtras(b);
							startActivity(eventScreen);
						}

					});
				}
			});

		}

	}
	
	

}
